#include <QMessageBox>

#include "formeditfeed.h"
#include "functions.h"
#include "definitions.h"


FormEditFeed::FormEditFeed(RssReader *reader, QWidget *parent, const QString &suggestedCategory, const QString &link) : QDialog(parent), ui(new Ui::FormEditFeed) {
    ui->setupUi(this);
    this->reader = reader;
    this->oldFeed = NULL;

    connect(ui->btnHelp, SIGNAL(clicked()), this, SLOT(showHelp()));
    connect(ui->btnTest, SIGNAL(clicked()), this, SLOT(testLink()));
    connect(ui->txtTitle, SIGNAL(textChanged(QString)), this, SLOT(checkFeed()));
    connect(ui->txtLink, SIGNAL(textChanged(QString)), this, SLOT(checkFeed()));
    connect(ui->cmbCategory, SIGNAL(editTextChanged(QString)), this, SLOT(checkFeed()));
    connect(ui->cmbEnc, SIGNAL(editTextChanged(QString)), this, SLOT(checkFeed()));
    connect(ui->txtNextLink, SIGNAL(textChanged(QString)), this, SLOT(checkLink()));
    connect(ui->btnNextLink, SIGNAL(clicked()), this, SLOT(advance()));

    ui->txtLink->setPlaceholderText(link);
    ui->txtNextLink->setPlaceholderText(link);
    ui->txtNextLink->setText(link);

    foreach (QString category, this->reader->getCategories()) {
        ui->cmbCategory->addItem(category);
        if (category == suggestedCategory)
            ui->cmbCategory->setCurrentIndex(ui->cmbCategory->count()-1);
    }

    if (this->reader->getCategories().size() == 0)
        ui->cmbCategory->setEditText(tr("Your new category's title"));
    QList<QByteArray> encodings = QTextCodec::availableCodecs();
    foreach (QByteArray encod, encodings)
        ui->cmbEnc->addItem(QString(encod));
}

FormEditFeed::~FormEditFeed() {
    delete ui;
}

void FormEditFeed::advance() {
    testLink(ui->txtNextLink->text());
    ui->stackedWidget->setCurrentIndex(ui->stackedWidget->currentIndex()+1);
}

RssFeed *FormEditFeed::editFeed(RssFeed *oldFeed) {
    if (oldFeed != NULL) {
        this->oldFeed = oldFeed;
        setWindowTitle(tr("Edit feed"));
        ui->txtTitle->setText(this->oldFeed->getTitle());
        ui->txtLink->setText(this->oldFeed->getLink());
        ui->cmbCategory->setEditText(this->oldFeed->getCategory());
        ui->cmbType->setCurrentIndex(this->oldFeed->getType() - FEED_UNKNOWN - 1);
        ui->cmbEnc->setEditText(this->oldFeed->getEncoding());
        ui->stackedWidget->setCurrentIndex(1);
        ui->txtLink->selectAll();
        ui->txtLink->setFocus();
    }
    ui->txtNextLink->selectAll();
    ui->txtNextLink->setFocus();
    if (this->exec() == QDialog::Accepted) {
        return new RssFeed(ui->txtTitle->text(), ui->txtLink->text(), ui->cmbCategory->currentText(), Functions::intToFeedType(ui->cmbType->currentIndex() + 1 + (int) FEED_UNKNOWN), ui->cmbEnc->currentText());
    }
    else {
        return NULL;
    }
}

void FormEditFeed::checkLink() {
    QString url = ui->txtNextLink->text();
    // Safari uses URL: feed://foo.bar/...
    if (url.startsWith("feed://")) {
        url = url.replace(QRegExp("^feed"), "http");
        ui->txtNextLink->setText(url);
        // it's fine to return here. We will get another call
        // immediately due setText()
        return;
    }
    // and feed:html:// sometimes too
    if (url.startsWith("feed:http")) {
        url = url.replace(QRegExp("^feed:http"), "http");
        ui->txtNextLink->setText(url);
        // it's fine to return here. We will get another call
        // immediately due setText()
        return;
    }
    ui->btnNextLink->setEnabled(Functions::isValid(QList<QString>() << url));
}

void FormEditFeed::checkFeed() {
    QStringList toCheck;
    toCheck << ui->txtTitle->text() << ui->txtLink->text() << ui->cmbEnc->currentText();
    // do not check ui->cmbCategory->currentText() against VALID_LIMIT. I want 2 chars catogory too.
    // also an empty caategory can be valid later
    QString category = ui->cmbCategory->currentText();
    if (category.isEmpty())
        category = tr("Default");

    if (Functions::isValid(toCheck)) {
        if (!oldFeed && reader->canBeAdded(ui->txtTitle->text(), ui->txtLink->text()))
            ui->btnOk->setEnabled(true);
        else if (oldFeed && reader->canBeEdited(oldFeed, new RssFeed(ui->txtTitle->text(), ui->txtLink->text(), category, Functions::intToFeedType(ui->cmbType->currentIndex() + 1 + (int) FEED_UNKNOWN), ui->cmbEnc->currentText())))
            ui->btnOk->setEnabled(true);
		else
            ui->btnOk->setEnabled(false);
    }
    else {
        ui->btnOk->setEnabled(false);
    }
}

void FormEditFeed::showHelp() {
    QMessageBox::information(this, tr("Help"), tr("Title must be at least three characters long.\n\nNote also that you can write your own names for category, you don't have to select predefined ones. The \"Test by link\" button is for testing if feed exists and you have to have link written in dialog already."));
}

bool FormEditFeed::testLink(const QString &link) {
    QString realLink = link == "" ? ui->txtLink->text() : link;
    QString *title = new QString();
    FeedType type = RssFeed::guessFeed(realLink, title);
    if (ui->txtNextLink->text().size() > 0 && link != "")
        ui->txtLink->setText(ui->txtNextLink->text());
    switch (type) {
        case FEED_UNKNOWN:
            QMessageBox::critical(this, tr("Feed doesn't exist"), tr("This feed doesn't exist or its unreachable. Please double-check url which you provided. You may have to input other details of feed by yourself."));
            return false;
        case FEED_ATOM:
        case FEED_RSS:
            QMessageBox::information(this, tr("Feed exists"), tr("It seems, that this feed exists and is accessible. You can add this feed without problems.\n\nObtained name: %1\nObtained type: %2\nObtained encoding: %3").arg(title->split(',').at(1), Functions::feedTypeToQstring(type), title->split(',').at(0).size() > 0 ? title->split(',').at(0) : tr("NO ENCODING FOUND, USING UTF-8")));
            break;
    }
    ui->txtTitle->setText(title->split(',').at(1));
    if (title->split(',').at(0).size() > 0)
        ui->cmbEnc->setEditText(title->split(',').at(0));
    else
        ui->cmbEnc->setEditText("UTF-8");
    ui->cmbType->setCurrentIndex(type - FEED_UNKNOWN - 1);
    return true;
}
